<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8" />
  <meta http-equiv="X-UA-Compatible" content="IE=edge" />
  <meta name="viewport" content="width=device-width, initial-scale=1.0" />
  <title>webRequest</title>
  <style>
  </style>
</head>

<body>
<pre>
// 自定义UA
function customUA() {
  const filter = {
    urls: ['https://*.github.com/*'],
  }
  session.defaultSession.webRequest.onBeforeSendHeaders(filter, (details, callback) => {
    details.requestHeaders['User-Agent'] = 'MyAwesomeAgent'
    callback({ requestHeaders: details.requestHeaders })
  })
}

// 绕过跨域限制
function simpleCors() {
  const filter = {
    urls: ['http://localhost:*/*'],
  }
  win.webContents.session.webRequest.onHeadersReceived(filter, (details, callback) => {
    const { responseHeaders } = details
    responseHeaders['Access-Control-Allow-Origin'] = ['*']
    callback({ responseHeaders })
  })
  win.loadFile(path.join(__dirname, '../renderer/index.html'))
}

// 请求转发
function redirect() {
  win.webContents.session.webRequest.onBeforeRequest(
    {
      urls: [],
    },
    (details, callback) => {
      const { url, resourceType } = details
      const response = { cancel: false }
      if (resourceType === 'xhr' && url.startsWith('http://localhost:3030')) {
        response.redirectURL = 'http://localhost:4040'
      }
      callback(response)
    },
  )
  win.loadFile(path.join(__dirname, '../renderer/index.html'))
}
</pre>
</body>

</html>